const BASE_URL = 'https://jsz315.xyz/uni-record'
// const BASE_URL = 'http://localhost:4500/uni-record'

class Request {
	async request(options = {}) {
		const {
			url,
			method = 'GET',
			data = {},
			header = {}
		} = options
		console.log('请求参数', url, method, data, header)

		return new Promise((resolve, reject) => {
			// 文件上传特殊处理
			if (options.isFileUpload) {
				// #ifdef H5
				const formData = new FormData()
				formData.append(data.name || 'file', data.file)
				if (data.formData) {
					Object.entries(data.formData).forEach(([key, value]) => {
						formData.append(key, value)
					})
				}

				const xhr = new XMLHttpRequest()
				xhr.open('POST', `${BASE_URL}${url}`)
				xhr.onload = () => {
					if (xhr.status >= 200 && xhr.status < 300) {
						resolve(JSON.parse(xhr.response))
					} else {
						reject(new Error(xhr.statusText || '上传失败'))
					}
				}
				xhr.onerror = () => reject(new Error('网络错误'))
				xhr.send(formData)
				// #endif

				// #ifdef APP-PLUS
				uni.uploadFile({
					url: `${BASE_URL}${url}`,
					filePath: data.file,
					name: data.name || 'file',
					formData: data.formData || {},
					header: {
						...header,
						'Content-Type': 'multipart/form-data'
					},
					success: (res) => {
						if (res.statusCode === 200) {
							resolve(typeof res.data === 'string' ? JSON.parse(res.data) : res
								.data)
						} else {
							reject(new Error(res.data?.message || '上传失败'))
						}
					},
					fail: (err) => {
						reject(new Error(err.errMsg || '上传请求失败'))
					}
				})
				// #endif
			} else {
				// 普通请求处理
				// #ifdef H5
				const isFormData = data instanceof FormData
				const fetchOptions = {
					method,
					headers: {
						'Content-Type': isFormData ? undefined : 'application/json',
						...header
					}
				}

				// GET 请求不能有 body，将参数转换为 URL 查询字符串
				let requestUrl = `${BASE_URL}${url}`
				if (method === 'GET' && Object.keys(data).length > 0) {
					const params = new URLSearchParams(data).toString()
					requestUrl = `${requestUrl}${requestUrl.includes('?') ? '&' : '?'}${params}`
				} else if (method !== 'GET') {
					fetchOptions.body = isFormData ? data : JSON.stringify(data)
				}

				fetch(requestUrl, fetchOptions)
					.then(async response => {
						const result = await response.json()
						return response.ok ? resolve(result) : reject(new Error(result.message))
					})
					.catch(err => {
						console.error("请求错误:", err)
						reject(new Error(err.message || '网络错误'))
					})
				// #endif

				// #ifdef APP-PLUS
				uni.request({
					url: `${BASE_URL}${url}`,
					method,
					data: method === 'GET' ? undefined : data, // GET 请求不传 data
					header: {
						'Content-Type': 'application/json',
						...header
					},
					success: (res) => {
						if (res.statusCode >= 200 && res.statusCode < 300) {
							resolve(res.data)
						} else {
							reject(new Error(res.data?.message || `请求失败 ${res.statusCode}`))
						}
					},
					fail: (err) => {
						reject(new Error(err.errMsg || '网络错误'))
					}
				})
				// #endif
			}
		})
	}

	// 文件上传方法
	upload(url, fileData) {
		return this.request({
			url,
			method: 'POST',
			data: fileData,
			isFileUpload: true
		})
	}

	uploadBase64(url, base64) {
		return new Promise(resolve => {
			uni.request({
				url: `${BASE_URL}${url}`,
				method: 'POST',
				data: {
					image: base64, // 这里是前面获取到的 base64 字符串
					name: "jsz"
				},
				header: {
					'content-type': 'application/json'
				},
				success: (response) => {
					console.log(response.data);
					resolve(response.data)
				},
				fail: (error) => {
					console.error(error);
					resolve(null)
				}
			});
		})
	}

	// 其他方法保持不变
	get(url, options = {}) {
		return this.request({
			url,
			method: 'GET',
			...options
		})
	}

	post(url, data, options = {}) {
		return this.request({
			url,
			method: 'POST',
			data,
			...options
		})
	}

	put(url, data, options = {}) {
		return this.request({
			url,
			method: 'PUT',
			data,
			...options
		})
	}

	delete(url, options = {}) {
		return this.request({
			url,
			method: 'DELETE',
			...options
		})
	}
}

export const request = new Request()